package com.ruoyi.web.controller.pack;

import java.util.List;
import javax.servlet.http.HttpServletResponse;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.pack.domain.PackLocator;
import com.ruoyi.pack.service.IPackLocatorService;
import com.ruoyi.pack.service.ILocationProcessingService;
import com.ruoyi.pack.dto.LocationUploadRequest;
import com.ruoyi.pack.dto.LocationUploadWrapper;
import com.ruoyi.pack.dto.ApiLocationData;
import com.ruoyi.common.config.YuntianxiaConfig;
import com.ruoyi.common.utils.SignatureUtils;

import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.math.BigDecimal;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;

/**
 * 定位器Controller
 *
 * @author ruoyi
 * @date 2024-01-01
 */
@RestController
@RequestMapping("/pack/locator")
public class PackLocatorController extends BaseController
{
    private static final Logger log = LoggerFactory.getLogger(PackLocatorController.class);

    @Autowired
    private IPackLocatorService packLocatorService;

    @Autowired
    private YuntianxiaConfig yuntianxiaConfig;

    @Autowired
    private ILocationProcessingService locationProcessingService;

    /**
     * 查询定位器列表
     */
    @PreAuthorize("@ss.hasPermi('pack:locator:list')")
    @GetMapping("/list")
    public TableDataInfo list(HttpServletRequest request)
    {
        startPage();

        // 手动构建PackLocator查询对象，避免自动参数绑定冲突
        PackLocator packLocator = new PackLocator();

        // 手动设置基本查询参数
        String locatorCode = request.getParameter("locatorCode");
        if (locatorCode != null && !locatorCode.trim().isEmpty()) {
            packLocator.setLocatorCode(locatorCode);
        }

        String containerCode = request.getParameter("containerCode");
        if (containerCode != null && !containerCode.trim().isEmpty()) {
            packLocator.setContainerCode(containerCode);
        }

        String bindStatus = request.getParameter("bindStatus");
        if (bindStatus != null && !bindStatus.trim().isEmpty()) {
            try {
                packLocator.setBindStatus(Integer.parseInt(bindStatus));
            } catch (NumberFormatException e) {
                log.warn("bindStatus参数格式错误: {}", bindStatus);
            }
        }

        String locatorStatus = request.getParameter("locatorStatus");
        if (locatorStatus != null && !locatorStatus.trim().isEmpty()) {
            packLocator.setLocatorStatus(locatorStatus);
        }

        // 处理排序参数
        String orderByColumn = request.getParameter("orderByColumn");
        String isAsc = request.getParameter("isAsc");
        if (orderByColumn != null && !orderByColumn.trim().isEmpty()) {
            // 将前端的驼峰命名转换为数据库字段名
            String dbColumnName = convertToDbColumnName(orderByColumn);
            String sortOrder = "desc".equalsIgnoreCase(isAsc) ? "desc" : "asc";
            packLocator.getParams().put("orderByColumn", dbColumnName);
            packLocator.getParams().put("isAsc", sortOrder);
            log.debug("设置排序参数: {} {}", dbColumnName, sortOrder);
        } else {
            // 默认按最后在线时间倒序排序
            packLocator.getParams().put("orderByColumn", "last_online_time");
            packLocator.getParams().put("isAsc", "desc");
            log.debug("使用默认排序: last_online_time desc");
        }

        // 处理最后在线时间范围参数 - 支持多种参数格式
        String[] lastOnlineTime = null;

        // 尝试获取数组格式参数: lastOnlineTime[0], lastOnlineTime[1]
        String startTime = request.getParameter("lastOnlineTime[0]");
        String endTime = request.getParameter("lastOnlineTime[1]");

        if (startTime != null && endTime != null) {
            lastOnlineTime = new String[]{startTime, endTime};
        } else {
            // 尝试获取标准数组格式参数: lastOnlineTime
            lastOnlineTime = request.getParameterValues("lastOnlineTime");
        }

        if (lastOnlineTime != null && lastOnlineTime.length >= 2) {
            String begin = lastOnlineTime[0];
            String end = lastOnlineTime[1];

            // 只有当时间值不为空时才添加查询条件
            if (begin != null && !begin.trim().isEmpty()) {
                packLocator.getParams().put("beginLastOnlineTime", begin);
            }
            if (end != null && !end.trim().isEmpty()) {
                packLocator.getParams().put("endLastOnlineTime", end);
            }

            log.debug("设置最后在线时间查询范围: {} 到 {}", begin, end);
        }

        log.debug("最终查询参数: locatorCode={}, containerCode={}, bindStatus={}, locatorStatus={}",
                 packLocator.getLocatorCode(), packLocator.getContainerCode(),
                 packLocator.getBindStatus(), packLocator.getLocatorStatus());

        List<PackLocator> list = packLocatorService.selectPackLocatorList(packLocator);
        return getDataTable(list);
    }

    /**
     * 将前端驼峰命名转换为数据库字段名
     */
    private String convertToDbColumnName(String camelCase) {
        if (camelCase == null || camelCase.isEmpty()) {
            return camelCase;
        }

        // 常用字段映射
        switch (camelCase) {
            case "locatorCode":
                return "locator_code";
            case "locatorStatus":
                return "locator_status";
            case "batteryLevel":
                return "battery_level";
            case "lastOnlineTime":
                return "last_online_time";
            case "createTime":
                return "create_time";
            case "updateTime":
                return "update_time";
            default:
                // 通用驼峰转下划线
                return camelCase.replaceAll("([A-Z])", "_$1").toLowerCase();
        }
    }

    /**
     * 导出定位器列表
     */
    @PreAuthorize("@ss.hasPermi('pack:locator:export')")
    @Log(title = "定位器", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, PackLocator packLocator)
    {
        List<PackLocator> list = packLocatorService.selectPackLocatorList(packLocator);
        ExcelUtil<PackLocator> util = new ExcelUtil<PackLocator>(PackLocator.class);
        util.exportExcel(response, list, "定位器数据");
    }

    /**
     * 获取定位器详细信息
     */
    @PreAuthorize("@ss.hasPermi('pack:locator:query')")
    @GetMapping(value = "/{locatorId}")
    public AjaxResult getInfo(@PathVariable("locatorId") Long locatorId)
    {
        return success(packLocatorService.selectPackLocatorByLocatorId(locatorId));
    }

    /**
     * 新增定位器
     */
    @PreAuthorize("@ss.hasPermi('pack:locator:add')")
    @Log(title = "定位器", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody PackLocator packLocator)
    {
        // 校验定位器编码唯一性
        if (!packLocatorService.checkLocatorCodeUnique(packLocator.getLocatorCode()))
        {
            return error("新增定位器'" + packLocator.getLocatorCode() + "'失败，定位器编码已存在");
        }

        return toAjax(packLocatorService.insertPackLocator(packLocator));
    }

    /**
     * 修改定位器
     */
    @PreAuthorize("@ss.hasPermi('pack:locator:edit')")
    @Log(title = "定位器", businessType = BusinessType.UPDATE)
    @PutMapping("/{locatorId}")
    public AjaxResult edit(@PathVariable("locatorId") Long locatorId, @RequestBody PackLocator packLocator)
    {
        packLocator.setLocatorId(locatorId);
        return toAjax(packLocatorService.updatePackLocator(packLocator));
    }

    /**
     * 删除定位器
     */
    @PreAuthorize("@ss.hasPermi('pack:locator:remove')")
    @Log(title = "定位器", businessType = BusinessType.DELETE)
    @DeleteMapping("/{locatorIds}")
    public AjaxResult remove(@PathVariable Long[] locatorIds)
    {
        return toAjax(packLocatorService.deletePackLocatorByLocatorIds(locatorIds));
    }

    /**
     * 更新定位器状态
     */
    @PreAuthorize("@ss.hasPermi('pack:locator:status')")
    @Log(title = "更新定位器状态", businessType = BusinessType.UPDATE)
    @PutMapping("/{locatorId}/status")
    public AjaxResult updateStatus(@PathVariable("locatorId") Long locatorId, @RequestBody UpdateStatusRequest request)
    {
        return toAjax(packLocatorService.updateLocatorStatus(locatorId,
            request.getLocatorStatus(), request.getBatteryLevel(), request.getSignalStrength()));
    }

    /**
     * 查询未绑定运单的定位器
     */
    @PreAuthorize("@ss.hasPermi('pack:locator:list')")
    @GetMapping("/unbound")
    public AjaxResult getUnboundLocators()
    {
        List<PackLocator> list = packLocatorService.selectUnboundLocators();
        return success(list);
    }

    /**
     * 查询已绑定运单的定位器
     */
    @PreAuthorize("@ss.hasPermi('pack:locator:list')")
    @GetMapping("/bound")
    public AjaxResult getBoundLocators()
    {
        List<PackLocator> list = packLocatorService.selectBoundLocators();
        return success(list);
    }

    /**
     * 获取定位器选项列表（用于下拉选择）
     */
    @PreAuthorize("@ss.hasPermi('pack:locator:list')")
    @GetMapping("/options")
    public AjaxResult getLocatorOptions()
    {
        // 查询定位器列表
        PackLocator packLocator = new PackLocator();
        packLocator.setLocatorStatus("1"); // 只查询状态正常的定位器
        List<PackLocator> list = packLocatorService.selectPackLocatorList(packLocator);

        // 转换为选项格式
        List<Map<String, Object>> options = new ArrayList<>();
        for (PackLocator locator : list) {
            Map<String, Object> option = new HashMap<>();
            option.put("value", locator.getLocatorId());
            option.put("label", locator.getLocatorCode());

            // 添加绑定的运单信息
            if (locator.getBoundContainer() != null) {
                option.put("waybillId", locator.getBoundContainer().getContainerId());
                option.put("waybillNo", locator.getBoundContainer().getContainerCode());
                option.put("senderName", locator.getBoundContainer().getMaterialCode());
                option.put("receiverName", locator.getBoundContainer().getMaterialName());
            }

            options.add(option);
        }

        return success(options);
    }

    /**
     * 根据定位器编码查询定位器
     */
    @PreAuthorize("@ss.hasPermi('pack:locator:query')")
    @GetMapping("/code/{locatorCode}")
    public AjaxResult getByCode(@PathVariable("locatorCode") String locatorCode)
    {
        return success(packLocatorService.selectPackLocatorByLocatorCode(locatorCode));
    }

    /**
     * 检查定位器编码唯一性
     */
    @GetMapping("/checkLocatorCodeUnique")
    public AjaxResult checkLocatorCodeUnique(String locatorCode)
    {
        return success(packLocatorService.checkLocatorCodeUnique(locatorCode));
    }

    /**
     * 导入定位器数据
     */
    @PreAuthorize("@ss.hasPermi('pack:locator:import')")
    @Log(title = "定位器", businessType = BusinessType.IMPORT)
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception
    {
        ExcelUtil<PackLocator> util = new ExcelUtil<PackLocator>(PackLocator.class);
        List<PackLocator> locatorList = util.importExcel(file.getInputStream());
        String operName = getUsername();
        String message = packLocatorService.importLocator(locatorList, updateSupport, operName);
        return success(message);
    }

    /**
     * 下载定位器导入模板
     */
    @PreAuthorize("@ss.hasPermi('pack:locator:import')")
    @PostMapping("/importTemplate")
    public void importTemplate(HttpServletResponse response)
    {
        ExcelUtil<PackLocator> util = new ExcelUtil<PackLocator>(PackLocator.class);
        util.importTemplateExcel(response, "定位器数据");
    }

    /**
     * 上传定位器位置信息（无需权限验证）
     * 支持GET请求进行签名验证，POST请求进行位置信息上传
     */
    @Anonymous
    @Log(title = "上传定位器位置信息", businessType = BusinessType.INSERT)
    @RequestMapping(value = "/location", method = {RequestMethod.POST, RequestMethod.GET})
    public Object uploadLocation(
            @RequestBody(required = false) LocationUploadWrapper wrapper,
            @RequestParam(value = "nonce", required = false) String nonce,
            @RequestParam(value = "signature", required = false) String signature,
            @RequestParam(value = "timestamp", required = false) String timestamp,
            HttpServletRequest httpRequest) {

        // 根据请求方法类型处理不同的逻辑
        if ("GET".equals(httpRequest.getMethod())) {
            // GET请求处理签名验证
            return handleSignatureVerification(nonce, signature, timestamp);
        } else {
            // POST请求处理位置上传
            return handleLocationUpload(wrapper);
        }
    }

    /**
     * 处理签名验证（GET请求）
     */
    @ResponseBody
    private String handleSignatureVerification(String nonce, String signature, String timestamp) {
        log.info("定位器位置接口签名验证: nonce={}, signature={}, timestamp={}", nonce, signature, timestamp);

        // 获取配置的token
        String token = yuntianxiaConfig.getToken();

        // 验证签名
        if (SignatureUtils.checkSignature(signature, timestamp, nonce, token)) {
            log.info("定位器位置接口签名验证成功，返回nonce: {}", nonce);
            return nonce;
        } else {
            log.warn("定位器位置接口签名验证失败，signature={}, timestamp={}, nonce={}", signature, timestamp, nonce);
            return "error";
        }
    }

    /**
     * 处理位置信息上传（POST请求）
     */
    private AjaxResult handleLocationUpload(LocationUploadWrapper wrapper) {
        try {
            // 检查请求体是否为空
            if (wrapper == null) {
                log.warn("位置信息上传请求体为空");
                return error("请求体不能为空，请发送JSON格式的位置数据");
            }

            // 记录原始请求数据
            log.info("收到位置信息原始请求数据: {}", wrapper);

            // 检查apiDate节点
            ApiLocationData apiData = wrapper.getApiDate();
            if (apiData == null) {
                log.warn("apiDate节点为空");
                return error("apiDate节点不能为空");
            }

            // 将ApiLocationData转换为LocationUploadRequest
            LocationUploadRequest request = convertToLocationUploadRequest(apiData);
            
            // 记录转换后的请求参数
            log.info("转换后的位置信息: 定位器编码={}, 经纬度=({},{})", 
                request.getLocatorCode(), request.getLongitude(), request.getLatitude());
            
            // 基础参数验证
            if (request.getLocatorCode() == null || request.getLocatorCode().trim().isEmpty()) {
                log.warn("定位器编码为空");
                return error("定位器编码不能为空");
            }
            
            if (request.getLongitude() == null) {
                log.warn("经度参数为空");
                return error("经度参数不能为空");
            }
            
            if (request.getLatitude() == null) {
                log.warn("纬度参数为空");
                return error("纬度参数不能为空");
            }
            
            boolean result = locationProcessingService.processLocationUpload(request);
            if (result) {
                return success("位置信息上传成功");
            } else {
                return error("位置信息上传失败，请检查参数或定位器编码是否正确");
            }
        } catch (IllegalArgumentException e) {
            log.warn("位置信息上传参数错误: {}", e.getMessage());
            return error("参数错误: " + e.getMessage());
        } catch (Exception e) {
            log.error("位置信息上传异常", e);
            return error("位置信息上传异常: " + e.getMessage());
        }
    }

    /**
     * 将ApiLocationData转换为LocationUploadRequest
     */
    private LocationUploadRequest convertToLocationUploadRequest(ApiLocationData apiData) {
        LocationUploadRequest request = new LocationUploadRequest();
        
        // 字段映射
        request.setLocatorCode(apiData.getDeviceCode());  // deviceCode -> locatorCode
        
        // 经纬度转换：字符串转BigDecimal
        if (apiData.getLongitude() != null && !apiData.getLongitude().trim().isEmpty()) {
            request.setLongitude(new BigDecimal(apiData.getLongitude()));
        }
        if (apiData.getLatitude() != null && !apiData.getLatitude().trim().isEmpty()) {
            request.setLatitude(new BigDecimal(apiData.getLatitude()));
        }
        
        // 电池电量转换：Double转Long
        if (apiData.getBatteryLevel() != null) {
            request.setBatteryLevel(apiData.getBatteryLevel().longValue());
        }
        
        // 信号强度转换：Integer转Long
        if (apiData.getCsq() != null) {
            request.setSignalStrength(apiData.getCsq().longValue());
        }
        
        return request;
    }

    /**
     * 位置上传接口状态检查（无权限验证）
     */
    @Anonymous
    @GetMapping("/location/status")
    public AjaxResult locationStatus() {
        Map<String, Object> data = new HashMap<>();
        data.put("status", "active");
        data.put("timestamp", new Date());
        data.put("description", "定位器位置上传接口运行正常");
        data.put("usage", "请使用POST方法发送JSON格式的位置数据");
        data.put("required_fields", new String[]{"locatorCode", "longitude", "latitude"});
        AjaxResult result = success("位置上传接口状态正常");
        result.put("data", data);
        return result;
    }

    /**
     * 测试用位置上传接口（无权限验证）
     */
    @PostMapping("/location/test")
    public AjaxResult testUploadLocation(@RequestBody LocationUploadRequest request) {
        try {
            boolean result = locationProcessingService.processLocationUpload(request);
            if (result) {
                return success("位置信息上传成功");
            } else {
                return error("位置信息上传失败");
            }
        } catch (Exception e) {
            return error("位置信息上传异常: " + e.getMessage());
        }
    }



    /**
     * 解绑运单
     */
    @PreAuthorize("@ss.hasPermi('pack:locator:edit')")
    @Log(title = "定位器解绑运单", businessType = BusinessType.UPDATE)
    @PutMapping("/unbind-shipment")
    public AjaxResult unbindShipment(@RequestBody UnbindRequest request) {
        try {
            Long[] locatorIds = request.getLocatorIds();
            if (locatorIds == null || locatorIds.length == 0) {
                return error("请选择要解绑的定位器");
            }

            int successCount = 0;
            for (Long locatorId : locatorIds) {
                // 获取定位器信息
                PackLocator locator = packLocatorService.selectPackLocatorByLocatorId(locatorId);

                // 检查是否已绑定（不为null、不为0、不为-1）
                if (locator != null && locator.getContainerId() != null &&
                    locator.getContainerId() != 0L && locator.getContainerId() != -1L) {



                    // 1. 解绑定位器表 - 将containerId设置为-1
                    locator.setContainerId(-1L);

                    locator.setUpdateTime(new Date());
                    locator.setUpdateBy(getUsername());

                    int locatorResult = packLocatorService.updatePackLocator(locator);

                    // 2. 记录解绑成功
                    if (locatorResult > 0) {
                        successCount++;
                    }
                }
            }

            return success("成功解绑 " + successCount + " 个定位器");
        } catch (Exception e) {
            return error("解绑运单异常: " + e.getMessage());
        }
    }





    /**
     * 解绑运单请求体
     */
    public static class UnbindRequest {
        private Long[] locatorIds;

        public Long[] getLocatorIds() {
            return locatorIds;
        }

        public void setLocatorIds(Long[] locatorIds) {
            this.locatorIds = locatorIds;
        }
    }

    /**
     * 更新定位器状态请求体
     */
    public static class UpdateStatusRequest {
        private String locatorStatus;
        private Long batteryLevel;
        private Long signalStrength;

        public String getLocatorStatus() {
            return locatorStatus;
        }

        public void setLocatorStatus(String locatorStatus) {
            this.locatorStatus = locatorStatus;
        }

        public Long getBatteryLevel() {
            return batteryLevel;
        }

        public void setBatteryLevel(Long batteryLevel) {
            this.batteryLevel = batteryLevel;
        }

        public Long getSignalStrength() {
            return signalStrength;
        }

        public void setSignalStrength(Long signalStrength) {
            this.signalStrength = signalStrength;
        }
    }
}
